from pywebio import pin

from emi.config import Config, ConfigItem, ConfigItemOption


class ConfigEditUI:

    def __init__(self, config: Config, name_space: str = None):
        self.config = config
        if name_space:
            self.NAME = f"_config_edit_{name_space}"
        else:
            self.NAME = f"_config_edit"


    def _put_config_item(self,config_item:ConfigItem):
        if isinstance(config_item,ConfigItemOption):
            default_value = config_item.default_value
            _option_data = []
            for index, s_stye in enumerate(config_item.option_names):
                _option_data.append({
                    "value": config_item.option_values[index],
                    "label": config_item.option_names[index],
                    "selected": config_item.option_values[index] == default_value
                })

            pin.put_select(f"{self.NAME}_{config_item.key}", _option_data)

        elif config_item.value_type == int or\
                config_item.value_type == float or \
                config_item.value_type == str :
            _type = 'text'
            if config_item.value_type == int:
                _type = 'number'
            if config_item.value_type == float:
                _type = 'float'
            pin.put_input(f"{self.NAME}_{config_item.key}",
                          type=_type,
                          label=config_item.label,
                          value=self.config.get_value(config_item),
                          help_text=config_item.desc)
        else:
            raise RuntimeError(f"不支持的类型ConfigItem: {config_item.value_type}")


    async def commit_action(self):
        """
        提交action操作。此时，将Input控件的值提交到config对象里面。
        """
        for config_item in self.config.get_items():
            _name = f"{self.NAME}_{config_item.key}"
            _value = await pin.pin[_name]
            if _value is None:
                self.config.set_value(config_item.key,None)
            else:
                self.config.set_value(config_item.key,config_item.value_type(_value))


    def show(self):
        for config_item in self.config.get_items():
            self._put_config_item(config_item)


